package com.ds.robot.assistant.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * 作用：
 *
 * @author WeiShaoying
 * 
 */
@Configuration
@Slf4j
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        log.info("RestTemplateConfig初始化, factory={}", factory);
        // 创建一个不跟随重定向的HttpClient
        // RequestConfig config = RequestConfig.custom()
        //         .setRedirectsEnabled(false) // 禁用重定向
        //         .build();
        // CloseableHttpClient httpClient = HttpClients.custom()
        //         .setDefaultRequestConfig(config)
        //         .build();
        //
        // // 使用自定义的HttpClient创建请求工厂
        // HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
        // SSLContext sslContext;
        // try {
        //     // 创建一个忽略所有证书验证的SSL上下文
        //     sslContext = new SSLContextBuilder()
        //             .loadTrustMaterial(null, (X509Certificate[] chain, String authType) -> true)
        //             .build();
        // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        //     throw new RuntimeException(e);
        // }
        // CloseableHttpClient httpClient = HttpClients.custom()
        //         .setSSLContext(sslContext)
        //         // 禁用主机名验证
        //         .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
        //         .build();
        // HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
        return new RestTemplate(factory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        // 设置连接超时时间和读取超时时间
        factory.setConnectTimeout(3000); // 毫秒
        factory.setReadTimeout(5000); // 毫秒
        return factory;
    }
}
